<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意：只允许为第三方分类设置相关参数！" type="warning" show-icon :closable='false' />
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader :options="cateList" v-model="selectedCatekeys" :props="cateProps" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button size='mini' :disabled='isBtnDisabled' type='primary' @click="addFormDialogvisible=true"
            style="margin-bottom:20px">添加参数
          </el-button>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button size='mini' :disabled='isBtnDisabled' type='primary' @click="addFormDialogvisible=true"
            style="margin-bottom:20px">添加属性
          </el-button>
        </el-tab-pane>
      </el-tabs>

      <el-table :data="manyTableData" border stripe v-if="activeName==='many'">
        <el-table-column type='expand'>
          <template slot-scope='scope'>
            <el-tag v-for='(i,index) in scope.row.attr_vals' :key='index' closable
              @close='handlerCLose(index,scope.row)'>
              {{i}}</el-tag>
            <el-input class="input-new-tag" @blur='handlerInputConfirm(scope.row)' size='small'
              v-model="scope.row.inputValue" v-if='scope.row.inputVisible'
              @keyup.13.native='handlerInputConfirm(scope.row)' style="width:100px;" ref='saveTagInput'>
            </el-input>
            <el-button class="button-new-tag" size='small' @click='  showInput(scope.row)' v-else>+new
              Tag
            </el-button>
          </template>
        </el-table-column>
        <el-table-column type='index'></el-table-column>
        <el-table-column label='参数名称' prop='attr_name'></el-table-column>
        <el-table-column label='操作'>
          <template slot-scope='scope'>
            <el-button type="primary" size="mini" class="el-icon-edit" @click="editList(scope.row.attr_id)">编辑
            </el-button>
            <el-button type="danger" size="mini" class="el-icon-delete" @click='deleteList(scope.row.attr_id)'>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-table :data="onlyTableData" border stripe v-else>
        <el-table-column type='expand'>
          <template slot-scope='scope'>
            <el-tag v-for='(i,index) in scope.row.attr_vals' :key='index'>{{i}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column type='index'></el-table-column>
        <el-table-column label='属性名称' prop='attr_name'></el-table-column>
        <el-table-column label='操作'>
          <template slot-scope="scope">
            <el-button type="primary" size="mini" class="el-icon-edit" @click="editList(scope.row.attr_id)">编辑
            </el-button>
            <el-button type="danger" size="mini" class="el-icon-delete" @click="deleteList(scope.row.attr_id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="' 添加'+ titleText" :visible.sync="addFormDialogvisible" width="50%" @close='addDialogClosed'>
      <el-form :model='addForm' :rules='addFormRule' ref='addFormRef' label-width='100px'>
        <el-form-item :label='titleText' prop='attr_name'>
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addFormDialogvisible = false" class="quxiao">Cancel</el-button>
        <el-button type="primary" @click="addParams">OK</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="'修改'+ titleText" :visible.sync="editFormDialogvisible" width="50%" @close='editDialogClosed'>
      <el-form :model='editForm' :rules='editFormRule' ref='editFormRef' label-width='100px'>
        <el-form-item :label='titleText' prop='attr_name'>
          <el-input v-model="editForm.attr_name" focus></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editFormDialogvisible = false" class="quxiao">Cancel</el-button>
        <el-button type="primary" @click="editParams">OK</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script scoped>
import { cateListAPI, paramsListAPI, paramsAddAPI, paramsEditAPI, EditAPI, deleteAPI } from '@/api/categories'
export default {
  // 组件名称
  name: 'demo',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: {},
  // 过滤器
  // 组件状态值
  data () {
    return {
      editForm: {
      },
      editFormRule: {
        attr_name: [{ required: true, message: '请输入参数名', trigger: 'blur' }]
      },
      addFormRule: {
        attr_name: [{ required: true, message: '请输入参数名', trigger: 'blur' }]
      },
      addForm: {
        attr_name: ''
      },
      editFormDialogvisible: false,
      addFormDialogvisible: false,
      activeName: 'many',
      selectedCatekeys: [],
      cateList: [],
      manyTableData: [],
      onlyTableData: [],
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      }
    }
  },
  // 计算属性
  computed: {
    titleText () {
      if (this.activeName === 'many') {
        return '动态属性'
      }
      return '静态参数'
    },
    isBtnDisabled () {
      if (this.selectedCatekeys.length !== 3) {
        return true
      }
      return false
    }
  },
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    handlerCLose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    handlerInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      this.saveAttrVals(row)
      row.inputVisible = false
    },
    async saveAttrVals (row) {
      const { data: res } = await EditAPI(this.cateId(), row.attr_id, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(',') })
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败！')
      this.$message({
        message: '修改参数成功',
        type: 'success'
      })
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus()
      })
    },
    deleteList (attr) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async _ => {
        await deleteAPI(this.cateId(), attr)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getparamsData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await EditAPI(this.cateId(), this.editForm.attr_id, { attr_sel: this.activeName, attr_name: this.editForm.attr_name })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message({
          message: 'Ok改成功',
          type: 'success'
        })
        this.getparamsData()
        this.editFormDialogvisible = false
      })
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    async editList (attrId) {
      const { data: res } = await paramsEditAPI(this.cateId(), attrId)
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.editForm = res.data
      this.editFormDialogvisible = true
    },
    async addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await paramsAddAPI(this.cateId(), {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message({
          message: '添加成功',
          type: 'success'
        })
      })
      this.addFormDialogvisible = false
      this.getparamsData()
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    handleClick () {
      this.getparamsData()
    },
    cateId () {
      if (this.selectedCatekeys.length === 3) {
        return this.selectedCatekeys[2]
      }
      return null
    },
    async getParamslist () {
      const { data: res } = await cateListAPI()
      this.cateList = res.data
    },
    handleChange () {
      this.getparamsData()
    },
    async getparamsData () {
      if (this.selectedCatekeys.length !== 3) {
        this.selectedCatekeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await paramsListAPI(this.cateId(), { sel: this.activeName })
      res.data.forEach(i => {
        i.attr_vals = i.attr_vals ? i.attr_vals.split(',') : []
        i.inputVisible = false
        i.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    }
  },
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
  */
  created () {
    this.getParamslist()
  },
  /**
  * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
  */
  mounted () {

  }
}
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin-right: 15px;
}
</style>
